package com.atguigu;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/7
 */
public class SyncVsReentrantLockDemo {
    public static void main(String[] args) {
        MyResource myResource = new MyResource();
        new Thread(() -> {
            try {
                myResource.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();
        new Thread(() -> {
            try {
                myResource.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }
}

class MyResource {
    public synchronized void m1() {
        System.out.println(Thread.currentThread().getName() + "\t" + "---come in");
        // 模拟长耗时任务
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Lock lock = new ReentrantLock();

    public void m2() throws InterruptedException {
        if (lock.tryLock(2, TimeUnit.SECONDS)) {
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "---come in");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "\t" + "---抢锁失败");
        }
    }
}
